import React, { PureComponent,Fragment } from 'react';
import { formatMessage } from 'umi/locale';
import {Button, Checkbox, DatePicker, Form, Layout, message, Modal, Select, Tooltip} from 'antd';
import Animate from 'rc-animate';
import { connect } from 'dva';
import router from 'umi/router';
import GlobalHeader from '@/components/GlobalHeader';
import TopNavHeader from '@/components/TopNavHeader';
import EditPassword from './EditPassword'
import styles from './Header.less';
import Authorized from '@/utils/Authorized';
import request from '@/utils/request';
import {renderSignalIntensity} from "@/utils/utils";
import ReactDataGrid from "react-data-grid";
import moment from "moment";
import forEach from "lodash/forEach";
import ReactEcharts from "echarts-for-react";
const Option = Select.Option;
const FormItem = Form.Item;
const { Header } = Layout;
@Form.create()
class HeaderView extends PureComponent {
  state = {
    visible: true,
    type:'pressure',
    historyData:[],
    searchParams:{
      start_date:moment(new Date()).add(-1,'day').format('YYYY-MM-DD'),
      end_date: moment(new Date()).format('YYYY-MM-DD'),

    }
  };

  static getDerivedStateFromProps(props, state) {
    if (!props.autoHideHeader && !state.visible) {
      return {
        visible: true,
      };
    }
    return null;
  }

  componentDidMount() {
    //document.addEventListener('scroll', this.handScroll, { passive: true });
    this.handleSearch(this.state.searchParams)

  }

  componentWillUnmount() {
   // document.removeEventListener('scroll', this.handScroll);
  }
  handleSearch=(searchParams)=>{
    const { compare_data } = this.props;
    const that = this;
    request(`/all_hydrant_historical_data`, {
      method: 'GET',
      params: {
        hydrant_ids: compare_data.map((item,index)=>{
          return item.id
        }).join(','),
        ...searchParams

      },
    }).then((response) => {
      console.log(response);
      if (response.status === 200) {
          this.setState({
            historyData: response.data.data
          });

      }

    });

  }
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const {
      searchParams,
      type
    } = this.state;
    return (
      <Form layout="inline" className="search-form">
        {/* <FormItem  label="类型">
          {getFieldDecorator('type', {
            initialValue: type,
          })(
            <Select onChange={(e)=>{
              this.setState({
                type:e
              })
            }} style={{width: '120px'}} >
              <Option value={'pressure'}>压力</Option>
              <Option value={'instantaneous_flow'}>累计流量</Option>
              <Option value={'cumulative_flow'}>瞬时流量</Option>
              <Option value={'temperature'}>温度</Option>
            </Select>,
          )}
        </FormItem> */}
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;
                console.log(fieldsValue)
                this.handleSearch({
                  start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
                  end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
        </FormItem>

      </Form>
    );
  }
  getOption = (name,key,color,unit) => {
    const that=this
    const { compare_data } = this.props;
    let names=compare_data.map((item,index)=>{
      return item.name
    })
    let series=[]
    console.log('names',names)
    const data = this.state.historyData;

    let diffData = [];
    let errDataIndex = [];
    let warmDataIndex = [];
    let difference_value = 0;
    let Date = [];
    forEach(data, (value, index) => {
      let Data = [];
      let parseData
      // for(let i=0;i<value.items.length;i++){
      //   console.log('(value.items[i].length',value.items.length)
      //   if(value.items.length>Date.length){
      //     Date.push(value.items[i].collected_at);
      //   }
      //   Data.push(value.items[i][key]);
      // }
      parseData = value.items.map((item2, index) => {

        return [(moment(item2.collected_at, "YYYY-MM-DD  HH:mm:ss").diff(moment(that.state.searchParams.start_date, "YYYY-MM-DD  HH:mm:ss"))) / 1000, item2[key]]
      });
      // console.log('parseData',parseData)
      series.push( {
        name: names[index],
        type: 'line',
        symbolSize: 8,
        data: parseData,
        smooth: true,
      },)

    });
    console.log('Date',Date)
    console.log('series',series)
    let gridLeft='2%';
    if(name==='压力'){
      gridLeft='3%'
    }
    if(name==='累计流量'){
      gridLeft='3%'
    }
    if(name==='瞬时流量'){
      gridLeft='2.2%'
    }
    if(name==='温度'){
      gridLeft='4.9%'
    }
    let option = {
      background: 'rgba(0,0,0,1)',
      tooltip: {
        trigger: 'axis',
        formatter: function (datas) {
          var res = ''
          for (var i = 0, length = datas.length; i < length; i++) {
            // console.log('datas[i]',datas[i])
            let time = (moment(that.state.searchParams.start_date).add(datas[i].data[0], 's')).format('MM-DD HH:mm:ss')
            // let time=''
            let value = datas[i].data[1]
            res +=time + '：' +  datas[i].seriesName + '：'
              + value + '<br/>'
          }
          return res
        }
      },
      legend: {
        data: names,
      },
      xAxis: [
        {
          type: 'value',
          // data: Date,
          axisLabel: {
            showMaxLabel: true,
            formatter: function (value, index) {
              return (moment(that.state.searchParams.start_date).add(value, 's')).format('MM-DD HH:mm:ss')
            }
          },
          axisPointer: {
            type: 'shadow',
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: name,
          axisLabel: {
            formatter: `{value}(${unit})`,
          },
        },
      ],
      grid: {
        top: '12%',
        left: gridLeft,
        right: '2%',
        bottom: '4%',
        containLabel: true,
      },
      dataZoom: [
        {
          type: 'slider',
          show: false,
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          xAxisIndex: [0],
        },
      ],
      series: series,
    };
    return option;
  };

  render() {
    const { compare_data } = this.props;
    return (
      <div>
        {this.renderSimpleForm()}
        <ReactEcharts
          option={this.getOption('压力','pressure','#1f58ff','MPa')}
          style={{ height: '300px', width: '100%'}}
          theme='my_theme'
          //onChartReady={this.onChartReadyCallback}
          //onEvents={EventsDict}
        />
        <ReactEcharts
          option={this.getOption('累计流量','cumulative_flow','#ff0090','m³')}
          style={{ height: '300px', width: '100%'}}
          theme='my_theme'
          //onChartReady={this.onChartReadyCallback}
          //onEvents={EventsDict}
        />
        <ReactEcharts
          option={this.getOption('瞬时流量','instantaneous_flow','#19d705','m³/h')}
          style={{ height: '300px', width: '100%'}}
          theme='my_theme'
          //onChartReady={this.onChartReadyCallback}
          //onEvents={EventsDict}
        />
        <ReactEcharts
          option={this.getOption('温度','temperature','#ffd230','℃')}
          style={{ height: '300px', width: '100%'}}
          theme='my_theme'
          //onChartReady={this.onChartReadyCallback}
          //onEvents={EventsDict}
        />

      </div>
    );
  }
}

export default connect(({ user, global, setting, loading }) => ({
  currentUser: user.currentUser,
  collapsed: global.collapsed,
  fetchingNotices: loading.effects['global/fetchNotices'],
  notices: global.notices,
  compare_data: global.compare_data,
  setting,
}))(HeaderView);
